package com.ruoyi.system.pool;

import cn.hutool.core.collection.CollUtil;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.ruoyi.system.domain.THost;
import com.ruoyi.system.mapper.THostMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 工厂
 * @author: stone
 * @date: Created by 2022/4/16 17:21
 * @version: 1.0.0
 * @pakeage: com.ruoyi.system.pool
 */
@Slf4j
@Component
public class SshClientFactory implements KeyedPooledObjectFactory<String, Session> {

    @Resource
    private THostMapper tHostMapper;

    @Override
    public PooledObject<Session> makeObject(String key) throws Exception {
        log.info("创建对象 =====> {}", key);
        THost host = new THost();
        host.setHostname(key);
        List<THost> tHosts = tHostMapper.queryAll(host);

        if (CollUtil.isEmpty(tHosts)) {
            log.info("没有这个服务器=======> {}", key);
            return null;
        }
        host = tHosts.get(0);
        JSch jSch = new JSch();
        Session session = jSch.getSession(host.getUsername(), key, host.getPort());
        session.setPassword(host.getPasswd());
        session.setTimeout(60 * 60 * 12);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(60000);
        return new DefaultPooledObject<>(session);

    }

    @Override
    public void destroyObject(String key, PooledObject<Session> pooledObject) throws Exception {
        log.info("销毁对象 ===> {}", key);
        Session session = pooledObject.getObject();
        session.disconnect();

    }

    @Override
    public boolean validateObject(String key, PooledObject<Session> pooledObject) {
        log.info("验证对象是否可用 ====> {}", key);
        Session session = pooledObject.getObject();
        if (session.isConnected()) {
            try {
                session.sendKeepAliveMsg();
                return true;
            } catch (Exception e) {
                log.info("ssh连接池中session连接实例已失效..." + key + ":" + session + ":" + e.getMessage());
                return false;
            }
        }
        return true;
    }

    @Override
    public void activateObject(String key, PooledObject<Session> pooledObject) throws Exception {
        //激活对象
        Session session = pooledObject.getObject();
        log.info("激活对象 ===> {} ==> {}", key, session);
    }

    @Override
    public void passivateObject(String key, PooledObject<Session> pooledObject) throws Exception {
        Session session = pooledObject.getObject();
        log.info("归还对象 ===> {} ==> {}", key, session);
    }
}
